from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routers import auth, admin, data_processing
from database import engine, Base
import os
from dotenv import load_dotenv

# 加载.env文件
load_dotenv()

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 运行数据库迁移
try:
    from migrate_database import migrate_database
    migrate_database()
except Exception as e:
    print(f"原数据库迁移警告: {e}")

# 运行用户权限管理迁移
try:
    from migrate_user_management import migrate_user_management
    migrate_user_management()
except Exception as e:
    print(f"用户权限管理迁移警告: {e}")

app = FastAPI(
    title="APIViewer Backend",
    description="医学图像查看器后端API",
    version="1.0.0"
)

# 环境变量配置
DEBUG = os.getenv("DEBUG", "true").lower() == "true"
ENVIRONMENT = os.getenv("ENVIRONMENT", "development")

# 配置CORS源
def get_cors_origins():
    """从环境变量获取CORS允许的源"""
    cors_origins_env = os.getenv("CORS_ORIGINS", "")
    
    if cors_origins_env:
        # 从环境变量解析，支持逗号分隔
        origins = [origin.strip() for origin in cors_origins_env.split(",") if origin.strip()]
        print(f"📝 从环境变量读取CORS源: {origins}")
        return origins
    
    # 默认配置
    if ENVIRONMENT == "production":
        # 生产环境默认配置
        default_origins = ["https://your-domain.com"]
        print(f"⚠️  使用生产环境默认CORS源: {default_origins}")
        print("💡 建议在.env文件中设置 CORS_ORIGINS 环境变量")
        return default_origins
    else:
        # 开发环境默认配置
        default_origins = [
            "http://localhost:3000",
            "http://127.0.0.1:3000",
            "http://localhost:3001",  # 备用端口
            "http://192.168.1.100:3000",  # 局域网IP（根据需要调整）
        ]
        print(f"🔧 使用开发环境默认CORS源: {default_origins}")
        return default_origins

ALLOWED_ORIGINS = get_cors_origins()

print(f"🌐 当前环境: {ENVIRONMENT}")
print(f"🌐 调试模式: {'开启' if DEBUG else '关闭'}")
print(f"🌐 最终CORS配置: {ALLOWED_ORIGINS}")

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
    allow_headers=["*"],
)

# 添加请求日志中间件（开发环境）
if DEBUG:
    @app.middleware("http")
    async def log_requests(request, call_next):
        import time
        start_time = time.time()
        
        # 记录请求信息
        print(f"🔍 请求: {request.method} {request.url}")
        print(f"🔍 Headers: {dict(request.headers)}")
        print(f"🔍 Origin: {request.headers.get('origin', 'None')}")
        
        response = await call_next(request)
        
        # 记录响应信息
        process_time = time.time() - start_time
        print(f"✅ 响应: {response.status_code} ({process_time:.3f}s)")
        print(f"✅ CORS Headers: {dict(response.headers)}")
        print("-" * 50)
        
        return response

# 包含路由
app.include_router(auth.router, prefix="/api/auth", tags=["authentication"])
app.include_router(admin.router, prefix="/api/admin", tags=["admin"])
app.include_router(data_processing.router, prefix="/api/data-processing", tags=["data-processing"])

@app.get("/")
async def root():
    return {"message": "APIViewer Backend API"}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

# CORS测试端点
@app.get("/api/test/cors")
async def test_cors():
    """测试CORS配置的端点"""
    return {
        "message": "CORS配置正常",
        "environment": ENVIRONMENT,
        "allowed_origins": ALLOWED_ORIGINS,
        "timestamp": os.popen("date").read().strip()
    }

@app.options("/api/test/cors")
async def cors_preflight():
    """处理预检请求"""
    return {"message": "preflight ok"}

# 添加测试POST端点
@app.post("/api/test/post")
async def test_post(data: dict):
    """测试POST请求的CORS"""
    return {
        "message": "POST请求成功",
        "received_data": data,
        "timestamp": os.popen("date").read().strip()
    }

# 注意：生产环境应使用 uvicorn 命令启动，而不是直接运行此文件
# 启动命令: uvicorn main:app --host 0.0.0.0 --port 8000 [--reload] 